package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pactera.madp.admin.api.constant.SyncConstant;
import com.pactera.madp.admin.api.entity.SysUser;
import com.pactera.madp.admin.api.entity.SysWxDeptRelation;
import com.pactera.madp.admin.api.feign.RemoteSyncSysService;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.cp.api.bo.SyncPsnInfoBo;
import com.pactera.madp.cp.api.entity.sync.SyncWxOrgRelation;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.RedisUtil;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.mapper.sync.SyncPsnInfoMapper;
import com.pactera.madp.cp.service.ICorpService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import com.pactera.madp.cp.service.sync.SyncBatchReplaceUserService;
import com.pactera.madp.cp.service.sync.SyncWxOrgRelationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class SyncBatchReplaceUserServiceImpl implements SyncBatchReplaceUserService {

    private final ICorpService corpService;
    private final IWorkEmployeeService workEmployeeService;
    private final SyncPsnInfoMapper syncPsnInfoMapper;
    private final RemoteSyncSysService remoteSyncSysService;
    private final SyncWxOrgRelationService syncWxOrgRelationService;
    private final RedisTemplate redisTemplate;
    private final SyncConfig syncConfig;

    @Override
    public boolean batchSyncUser() {
        String nowDate = DateUtil.format(new Date(), Constants.DATE_FORMAT);
        Integer corpId = corpService.list().get(0).getCorpId();

        // 锁定
        String lockKey = RedisUtil.buildKey(Constants.SYNC_PSN_BUSINESS_WX2SYS_LOCK, nowDate);
        boolean isLocked = RedisUtil.getLock(lockKey, 1, Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        if (!isLocked) {
            return false;
        }
        try {
            // 同步人力资源人员到CP
            workEmployeeService.syncEmployee(corpId);

            // 同步人力资源人员到系统
            doBatchSync();
        } finally {
            RedisUtil.del(lockKey);
        }

        return true;
    }

    private void doBatchSync() {
        // 查询人力资源员工列表
        List<SyncPsnInfoBo> boList = syncPsnInfoMapper.listPsn(Constants.SYNC_DEL_FLAG);

        // 过滤出指定人员
        boList = filterAppointPsn(boList);

        // 查询系统部门与企业微信部门关联列表
        List<SysWxDeptRelation> wxDeptList = remoteSyncSysService.getSysWxRelations(SecurityConstants.FROM_IN).getData();
        Map<Integer,Integer> wxDeptMap = new HashMap<>();
        wxDeptList.forEach(rel -> wxDeptMap.put(rel.getWxDeptId(), rel.getSysDeptId()));

        // 查询人力资源机构与企业微信部门关联列表
        List<SyncWxOrgRelation> orgWxList = syncWxOrgRelationService.list();
        Map<String, Integer> orgWxMap = new HashMap<>();
        orgWxList.forEach(rel -> orgWxMap.put(rel.getHrOrgId(), rel.getWxDeptId()));

        // 获取删除的企微部门与机构关联列表
        String key = RedisUtil.buildKey(SyncConstant.SYNC_WX_ORG_DEL_LIST, DateUtil.format(new Date(), Constants.DATE_FORMAT));
        List<SyncWxOrgRelation> delList = redisTemplate.opsForList().range(key, 0, -1);
        if (delList != null && !delList.isEmpty()) {
            delList.forEach(rel -> orgWxMap.put(rel.getHrOrgId(), rel.getWxDeptId()));
        }

        // 获取删除的企业微信与系统部门关联列表
        key = RedisUtil.buildKey(SyncConstant.SYNC_WX_SYS_DEL_LIST, DateUtil.format(new Date(), Constants.DATE_FORMAT));
        List<SysWxDeptRelation> delWxDeptList = redisTemplate.opsForList().range(key, 0, -1);
        if (delWxDeptList != null && !delWxDeptList.isEmpty()) {
            delWxDeptList.forEach(rel -> wxDeptMap.put(rel.getWxDeptId(), rel.getSysDeptId()));
        }

        // 设置同步用户信息
        List<SysUser> userList = new ArrayList<>();
        SysUser sysUser = new SysUser();
        boList.forEach(bo -> {
            String mobile = bo.getMobile();
            if (StrUtil.isEmpty(mobile)) {
                log.error("手机号为空：" + bo.getJobNo());
                return;
            } else {
                mobile = mobile.length() > 11 ? mobile.substring(0, 11) : mobile;
            }
            boolean isOk = true;
            Integer sysDeptId = wxDeptMap.get(orgWxMap.get(bo.getUnit()));
            isOk = ObjectUtil.isNull(sysDeptId) ? false : true;
            if (!isOk) {
                return;
            }
            SysUser user = sysUser.clone();
            user.setUsername(bo.getJobNo());
            user.setName(bo.getUserName());
            user.setPhone(mobile);
            user.setDeptId(sysDeptId);
            user.setCertNo(bo.getCertNo());
            user.setAvatar(bo.getEmpPhot());
            user.setLockFlag("9"); //同步后状态设置为禁用
            user.setDelFlag("0");
            userList.add(user);
        });

        if (userList.isEmpty()) {
            log.info("同步用户列表为空");
            return;
        }

        //远程同步服务调用
        Map<String,String> userMap = new HashMap<>(1);
        userMap.put("users", JSONUtil.toJsonStr(userList));
        remoteSyncSysService.onSyncWxEmp(userMap,SecurityConstants.FROM_IN);
        log.info("开始远程同步企业微信成员到MADP系统");
    }

    // 过滤出指定人员
    private List<SyncPsnInfoBo> filterAppointPsn(List<SyncPsnInfoBo> psnList) {
        List<SyncPsnInfoBo> newPsnList = new ArrayList<>();
        if (syncConfig.getPsnCtrlFlag()) {
            Set<String> jobNoList = syncConfig.getPsnJobNo();
            log.info("过滤人员：{}", jobNoList);
            for (SyncPsnInfoBo p : psnList) {
                if (jobNoList.contains(p.getJobNo())) {
                    newPsnList.add(p);
                    log.info("已过滤出人员：{}", p.getJobNo());
                }
            }
            return newPsnList;
        }
        return psnList;
    }

}
